package cn.zbh.exception;

import cn.zbh.enums.GlobalEnum;
import cn.zbh.result.JSONResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalException extends RuntimeException{

    @ExceptionHandler(Exception.class)
    public JSONResult exceptionHandler(Exception e){
        e.printStackTrace();
        log.info("全局异常"+e.getMessage());
        return JSONResult.error(GlobalEnum.ERROR);
    }


    @ExceptionHandler(GlobalCustomException.class)
    public JSONResult globalCustomException(GlobalCustomException e){
        e.printStackTrace();
        log.info("自定义异常");
       //return JSONResult.error("自定义报错了","-1");
        return JSONResult.error(e);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JSONResult methodArgumentNotValidException(MethodArgumentNotValidException me){
        me.printStackTrace();

        StringBuilder builder = new StringBuilder();

        me.getBindingResult().getAllErrors().forEach(errors->{
            builder.append(errors.getDefaultMessage()).append(",");
        });
        log.info("枚举异常");
        //return JSONResult.error("自定义报错了","-1");
        return JSONResult.error(builder.toString());
    }

}
